package ma.xin.shi;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

/*
* 参数说明：
*     parent:父容器
*     style：风格
*     labelText： lable
*     availableOptions: 给用户展示的选项
*     parentColumnCount: 父容器的列数，为了保证对齐，让lable、text、加号、减号在同一行
*  
*    // 示例一：父容器是 2 列
* new CheckableSelectText(parent, SWT.NONE, "选择内容:", new String[]{"A", "B", "C"}, 2);
*
*	// 示例二：父容器是 3 列
* new CheckableSelectText(parent, SWT.NONE, "选择内容:", new String[]{"A", "B", "C"}, 3);
*
*	// 示例三：兼容旧写法（默认 2 列）
* new CheckableSelectText(parent, SWT.NONE, "选择内容:", new String[]{"A", "B", "C"});
* 
* 示例调用：
* private static CheckableSelectText CstServer;
* private static CheckableSelectText CstClient;
*
* private static void AddECUsEndpointView(Composite parent) {
*    // 选项数据
*    String[] options = {
*        "VechileBody", "VCC_MCU", "VCC_MPU", "TMS", "VCU", "FLZCU", "FRZCU", "RZCU",
*        "ICC", "ICC_8155_Android", "ICC_8155_QNX", "TBOX", "TBOX_ex", "ADCC", "LCM",
*        "FCM", "FLM", "OTA", "AdvanceService", "VDS", "TBOXPackage"
*    };
*
*    // 创建两个控件，并让它们各占两列
*    CstServer = new CheckableSelectText(parent, SWT.NONE, "ECU Server：", options, 2);
*    CstClient = new CheckableSelectText(parent, SWT.NONE, "ECU Client：", options, 2);
*
*    // 设置默认值（可选）
*    CstServer.setSelectedItems(new String[]{"VCC_MCU", "TBOX"});
*    CstClient.setSelectedItems(new String[]{"ICC", "VCU"});
*
*    // 添加一个调试按钮
*    Button debugButton = new Button(parent, SWT.PUSH);
*    debugButton.setText("打印当前配置");
*    debugButton.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, false, 2, 1));
*
*    debugButton.addSelectionListener(new SelectionAdapter() {
*        @Override
*        public void widgetSelected(SelectionEvent e) {
*            System.out.println("=== 当前 ECU 配置 ===");
*
*            String[] serverItems = CstServer.getSelectedItems();
*            System.out.print("ECU Server: ");
*            System.out.println(Arrays.toString(serverItems));
*
*            String[] clientItems = CstClient.getSelectedItems();
*           System.out.print("ECU Client: ");
*            System.out.println(Arrays.toString(clientItems));
*        }
*    });
*}
*
*/
public class CheckableSelectText extends Composite {

    private Text text;
    private List<String> selectedItems = new ArrayList<>();

    // 构造方法（新增 int parentColumnCount 参数）
    public CheckableSelectText(Composite parent, int style, String labelText,
                               String[] availableOptions, int parentColumnCount) {
        super(parent, SWT.NONE);
        createContents(labelText, availableOptions, parentColumnCount);
    }

    // 构造方法（向后兼容：默认 parentColumnCount = 2）
    public CheckableSelectText(Composite parent, int style, String labelText,
                               String[] availableOptions) {
        this(parent, style, labelText, availableOptions, 2);
    }

	public Text getTextControl() {
        return text;
    }

    private void createContents(String labelText, String[] availableOptions, int parentColumnCount) {
        this.setLayout(new GridLayout(4, false));

        // 设置 LayoutData，关键：占满整行
        GridData gd = new GridData(SWT.FILL, SWT.CENTER, true, false);
        gd.horizontalSpan = parentColumnCount; // 占满父容器的当前行
        this.setLayoutData(gd);

        // Label
        Label label = new Label(this, SWT.NONE);
        label.setText(labelText);

        // Text (read-only)
        text = new Text(this, SWT.BORDER | SWT.READ_ONLY);
        text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));

        // Add Button (+)
        Button addButton = new Button(this, SWT.PUSH);
        addButton.setText("+");
        addButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));

        // Remove Button (-)
        Button removeButton = new Button(this, SWT.PUSH);
        removeButton.setText("-");
        removeButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));

        // 按钮事件：打开多选对话框进行添加
        addButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                MultiSelectDialog dialog = new MultiSelectDialog(getShell(), availableOptions, selectedItems.toArray(new String[0]));
                if (dialog.open() == Dialog.OK) {
                    selectedItems.clear();
                    selectedItems.addAll(Arrays.asList(dialog.getSelectedItems()));
                    updateTextDisplay();
                }
            }
        });

        // 删除按钮事件：打开多选对话框进行删除
        removeButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                MultiSelectDialog dialog = new MultiSelectDialog(getShell(), selectedItems.toArray(new String[0]), selectedItems.toArray(new String[0]));
                if (dialog.open() == Dialog.OK) {
                    selectedItems.clear();
                    selectedItems.addAll(Arrays.asList(dialog.getSelectedItems()));
                    updateTextDisplay();
                }
            }
        });
    }

    private void updateTextDisplay() {
        text.setText(selectedItems.isEmpty() ? "" : String.join(", ", selectedItems));
    }

    /**
     * 获取当前选中的所有项
     */
    public String[] getSelectedItems() {
        return selectedItems.toArray(new String[0]);
    }

    /**
     * 设置默认选中的项
     */
    public void setSelectedItems(String[] items) {
        selectedItems.clear();
        if (items != null) {
            selectedItems.addAll(Arrays.asList(items));
        }
        updateTextDisplay();
    }

    // 内部类：多选对话框
    private static class MultiSelectDialog extends Dialog {

        private CheckboxTableViewer viewer;
        private String[] allItems;
        private String[] initialSelection;
        private List<String> result = new ArrayList<>();

        protected MultiSelectDialog(Shell parentShell, String[] items, String[] selected) {
            super(parentShell);
            this.allItems = items;
            this.initialSelection = selected;
        }

        @Override
        protected void configureShell(Shell newShell) {
            super.configureShell(newShell);
            newShell.setText("选择项目");
        }

        @Override
        protected Control createDialogArea(Composite parent) {
            Composite container = (Composite) super.createDialogArea(parent);

            viewer = CheckboxTableViewer.newCheckList(container, SWT.BORDER);
            viewer.setContentProvider(ArrayContentProvider.getInstance());
            viewer.setLabelProvider(new LabelProvider());
            viewer.setInput(allItems);

            for (String item : initialSelection) {
                viewer.setChecked(item, true);
            }

            return viewer.getControl();
        }

        @Override
        protected void createButtonsForButtonBar(Composite parent) {
            createButton(parent, IDialogConstants.OK_ID, "完成", true);
            createButton(parent, IDialogConstants.CANCEL_ID, "取消", false);
        }

        @Override
        protected void okPressed() {
            Object[] checkedElements = viewer.getCheckedElements();
            for (Object obj : checkedElements) {
                result.add(obj.toString());
            }
            super.okPressed();
        }

        public String[] getSelectedItems() {
            return result.toArray(new String[0]);
        }
    }

}

